package com.bootdo.system.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import com.bootdo.system.domain.CompanyDO;
import com.bootdo.system.domain.CompanyPictureDO;
import com.bootdo.system.domain.SowingmapDO;
import com.bootdo.system.domain.WechatDO;
import com.bootdo.system.domain.WechatPicDO;
import com.bootdo.system.service.CompanyPictureService;
import com.bootdo.system.service.CompanyService;

import cn.hutool.core.util.StrUtil;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.OssUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

@Controller
@RequestMapping("/system/company")
public class CompanyController {
	@Autowired
	private CompanyService companyService;
	@Autowired
	private BootdoConfig bootdoConfig;
	
	@Autowired
	private CompanyPictureService companyPictureService;

	@GetMapping()
	String Company() {
		return "system/company/company";
	}

	@ResponseBody
	@GetMapping("/list")
	@Cacheable(value = "app", key = "'company'")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<CompanyDO> companyList = companyService.list(query);
		int total = companyService.count(query);
		PageUtils pageUtils = new PageUtils(companyList, total);
	
		return pageUtils;
	}
	
	/**
	 * @Title: getById  
	 * @Description: TODO(获取单个分公司)
	 * @author: lzy
	 * @date: 2018年5月24日 下午5:26:02
	 */
	@ResponseBody
	@GetMapping("/getById")
	public Map<String, Object> getById(@RequestParam("id") int id) {
		CompanyDO companyDO = companyService.get(id);
		Map<String, Object> map = new HashMap<>();
		map.put("companyId", id);
	    List<CompanyPictureDO>  piclist = companyPictureService.list(map);
		Map<String, Object> allmap = new HashMap<>();
		allmap.put("company", companyDO);
		allmap.put("picList", piclist);
		return allmap;
	}

	@GetMapping("/add")
	String add() {
		return "system/company/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Integer id, Model model) {
		CompanyDO company = companyService.get(id);
		model.addAttribute("company", company);
		return "system/company/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@CacheEvict(value = "app", key = "'company'")
	public R save(@RequestParam("file") MultipartFile file, CompanyDO company) {
		String URL = null;
		try {
			URL = OssUtil.fileUpload(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		company.setCompanyUrl(URL); 
		company.setAddTime(new Date());
		if (companyService.save(company) > 0) {
			return R.ok(""+company.getId()+"");
		}else {
			return R.error("保存失败");
		}
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@CacheEvict(value = "app", key = "'company'")
	public R update( CompanyDO company) {
        int update = companyService.update(company);
        if(update == 1 ){
        	return 	R.ok("修改成功");
        }else{
        	return R.error("修改失败");
        }
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@CacheEvict(value = "app", key = "'company'")
	public R remove(int id) {
		String imgUrl = null;
		try {
			imgUrl =companyService.get(id).getCompanyUrl().substring(45, 62);
		} catch (Exception e) {
		}
		Map<String, Object> map = new HashMap<>();
		map.put("companyId", id);
		List<CompanyPictureDO> list = companyPictureService.list(map);
		if (companyService.remove(id) > 0 && companyPictureService.remove(id) > 0) {
			OssUtil.deleteBucketInfo(imgUrl);
			if(list!=null & list.size()>0){
				for (CompanyPictureDO companyPictureDO : list) {
					String imgUrl1=companyPictureDO.getUrl().substring(45, 62);
					OssUtil.deleteBucketInfo(imgUrl1);
				}
			}
			return R.ok();
		} else {
			return R.error();
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Integer[] ids) {
		companyService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * @Title: upload
	 * @Description: TODO(图片上传的方法)
	 * @author: lzy
	 * @date: 2018年5月22日 下午3:03:42
	 */
	String upload(@RequestParam("file") MultipartFile file) {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		try {
			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);

		} catch (Exception e) {

		}
		return "/files/" + fileName;

	}
	
	
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/saveInput")
	public R saveInput(String test) {
         if(StrUtil.isBlank(test)){
        	 return R.error("上传出错");
         }
		return R.ok("上传成功");
	}
	
	
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/saveDemo")
	public R saveDemo(@RequestParam("img") MultipartFile[] img,String id) {
		String url = null;
		try {
		    for (MultipartFile file : img) {
		    	url = OssUtil.fileUpload(file);
		    	CompanyPictureDO companyPictureDO=new CompanyPictureDO();
				companyPictureDO.setUrl(url);
				companyPictureDO.setCompanyId(Integer.parseInt(id));
				companyPictureService.save(companyPictureDO);
			}			
		} catch (IOException e) {
			e.printStackTrace();
			return R.error();
		}
		return R.ok();
	}
	
	
	//排序跳转
	@GetMapping("/sort/{id}")
	@CacheEvict(value = "app", key = "'company'")
	public String sort(@PathVariable("id") Integer id,Model model) {
		model.addAttribute("id", id);
		return "system/company/sort";
	}

	//排序更新
	@ResponseBody
	@PostMapping("/sortUpdate")
	@CacheEvict(value = "app", key = "'company'")
	public R sortUpdate(CompanyDO companyDo) {
		int update = companyService.update(companyDo);
		if(update == 1){
			return R.ok("修改成功");
		}else {
			return R.error("修改失败");
		}
		
	}
	
	//跳转公司logo修改界面
	@GetMapping("/logo/{id}")
	String editLogo2(@PathVariable("id") Integer id, Model model) {
		CompanyDO companyDO = companyService.get(id);
		model.addAttribute("id",id);
		model.addAttribute("logoUrl",companyDO.getCompanyUrl());
		return "system/company/logo";
	}
	
	
	/**
	 * 公司logo修改
	 */
	@ResponseBody
	@PostMapping("/editLogo")
	@CacheEvict(value = "app", key = "'company'")
	public R saveLogo(@RequestParam("img") MultipartFile img,Integer id){
		CompanyDO companyDO = companyService.get(id);
		String imgUrl=companyDO.getCompanyUrl().substring(45, 62);
		OssUtil.deleteBucketInfo(imgUrl);
		String url =null;
		try {
			 url = OssUtil.fileUpload(img);
			 CompanyDO company = new  CompanyDO();
			 company.setId(id);
			 company.setCompanyUrl(url);
			 companyService.update(company);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return R.error("网络异常");

		}
		return R.ok();

	
			
			
	}
	
	
	
}
